package com.team.weigou.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSON;
import com.etsy.android.grid.StaggeredGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.team.weigou.R;
import com.team.weigou.adapter.HotInfoAdapter;
import com.team.weigou.bean.HotinfoData;
import com.team.weigou.config.UrlConfig;
import com.team.weigou.ui.GoodsActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Wangs on 2015/7/9.
 */
public class XinpinFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<StaggeredGridView>, AdapterView.OnItemClickListener {
    private HttpUtils httpUtils = new HttpUtils();
    private BitmapUtils bitmapUtils;

    //自定义下拉刷新瀑布流
    private PullToRefreshStaggeredGridView prrsgv;
    private StaggeredGridView staggeredGridView;
    private HotInfoAdapter adapter;
    private ArrayList<HotinfoData> list = new ArrayList<>();
    private String keywords;
    private boolean isClear;

    private int page = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBitmUtils();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hotinfo_layout, null);

        Bundle data = getArguments();//获得从activity中传递过来的值
        keywords = data.getString("keywords");
        initView(view, inflater);
        initData();
        return view;
    }

    /**
     * 初始化BitmapUtils工具类
     */
    private void initBitmUtils() {
        bitmapUtils = new BitmapUtils(getActivity());
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.ic_empty);
        bitmapUtils.configDefaultLoadingImage(R.mipmap.ic_empty);
    }

    //初始化瀑布流控件相关参数
    private void initView(View view, LayoutInflater inflater) {
        prrsgv = (PullToRefreshStaggeredGridView) view.findViewById(R.id.hotinfo_Gridview);
        prrsgv.setMode(PullToRefreshBase.Mode.BOTH);
        prrsgv.setOnRefreshListener(this);
        prrsgv.setOnItemClickListener(this);
        staggeredGridView = prrsgv.getRefreshableView();
        adapter = new HotInfoAdapter(getActivity(),list,bitmapUtils);
        prrsgv.setRefreshing();
        prrsgv.setAdapter(adapter);
    }

    private void initData() {
        getDataFromServer(UrlConfig.HOT_INFO_URL, adapter, list, prrsgv, isClear);
    }

    /**
     * pageSize=16&pageNo=1
     *
     * @return
     */

    private RequestParams getRequestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("orderType", "newOn_desc");
        params.addBodyParameter("row", "16");
        params.addBodyParameter("pageNo",String.valueOf(page));
        params.addBodyParameter("keywords", keywords);
        return params;
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        page = 1;
        list.clear();
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        page++;
        initData();
    }

    public void getDataFromServer(String url, final BaseAdapter adapter, final List<HotinfoData> list, final PullToRefreshBase pullToRefreshBase, final boolean isClear) {
        RequestParams params = getRequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, url,params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            String json = responseInfo.result;
                            String msg = new JSONObject(json).optString("msg");
                            if ("获取成功".equals(msg)) {
                                JSONArray arr = new JSONObject(json).getJSONArray("data");
                                List<HotinfoData> datas = JSON.parseArray(arr.toString(), HotinfoData.class);
                                if (isClear) {
                                    list.clear();
                                }
                                list.addAll(datas);
                                adapter.notifyDataSetChanged();
                                pullToRefreshBase.onRefreshComplete();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                    }
                }
        );
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), GoodsActivity.class);
        intent.putExtra("shopId", list.get(position).getShopId());
        intent.putExtra("name", list.get(position).getName());
        intent.putExtra("price",list.get(position).getPrice());
        intent.putExtra("value", list.get(position).getValue());
        intent.putExtra("image", list.get(position).getImage());
        startActivity(intent);
    }

}
